/*
* $Id: ChangePointOperation.cpp 336 2011-09-28 06:06:36Z volok-aleksej@yandex.ru $
*
* Copyright 2009-2011 by Volokitin Aleksey
* All rights reserved
*
*/
#include "Common/include.h"
#include "ChangePointOperation.h"
#include "Threads/ComReader.h"
#include "Database/TransactManager.h"
#include "Database/Tables/PointsTable.h"
#include "Database/Tables/FieldValuesTable.h"

CChangePointOperation::CChangePointOperation(CTransactManager* pManager)
: m_pManager(pManager){}
CChangePointOperation::~CChangePointOperation(){}

std::tstring CChangePointOperation::ExecuteOperation(IDatabase* pDatabase, IReader* pReader){
	CPointsTable points;
	CFieldValuesTable fieldValue;
	int size;
	pReader->ReadInt(size);
	int lenData = 0;
	int idPoint;
	lenData = pReader->ReadInt(idPoint);
	lenData += pReader->ReadUTF(points.m_content.s_strName);
	std::tstring strNamePoint = points.m_content.s_strName;
	lenData += pReader->ReadUTF(points.m_content.s_strNote);
	int idRecord;
	lenData += pReader->ReadInt(idRecord);
	if(idRecord != 0)
		points.m_content.s_nIdRecord = m_pManager->GetRealId(
			CTransactManager::ID(CTransactManager::FIELD_VALUE, idRecord));
	points.m_content.s_nId = m_pManager->GetRealId(
		CTransactManager::ID(CTransactManager::POINT, idPoint));
	points.UpdateValue(pDatabase);
	while (lenData < size){
		bool bExist = false;
		lenData += pReader->ReadInt(idRecord);
		idRecord = m_pManager->GetRealId(
			CTransactManager::ID(CTransactManager::FIELD_VALUE, idRecord));
		fieldValue.m_content.s_nId = idRecord;
		IResult* pResult = fieldValue.GetValue(pDatabase);
		if(pResult->GetSizeResult())
			bExist = true;
		pResult->Free();
		fieldValue.m_content.s_nId = idRecord;
		lenData += pReader->ReadUTF(fieldValue.m_content.s_strName);
		lenData += pReader->ReadUTF(fieldValue.m_content.s_strValue);
		lenData += pReader->ReadInt((int&)fieldValue.m_content.s_type);
		if(bExist)
			fieldValue.UpdateValue(pDatabase);
		else
			fieldValue.SetValue(pDatabase);
	}
	std::tstring strLog = ILanguageManager::GetLanguageManager()->GetString(CHANGE_POINT_LOG_ID);
	return strLog + _T(" ") + strNamePoint;
}

void CChangePointOperation::Free(){
	delete this;
}
